package cn.edu.xmu.oomall.customer.controller;

import cn.edu.xmu.javaee.core.aop.Audit;
import cn.edu.xmu.javaee.core.aop.LoginUser;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.core.model.ReturnObject;
import cn.edu.xmu.javaee.core.model.dto.UserDto;
import cn.edu.xmu.javaee.core.model.vo.PageVo;
import cn.edu.xmu.oomall.customer.controller.vo.CouponVo;
import cn.edu.xmu.oomall.customer.dao.bo.Coupon;
import cn.edu.xmu.oomall.customer.service.CouponService;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import cn.edu.xmu.javaee.core.util.CloneFactory;

import java.util.List;

/**
 * @author Suave
 * @date 2024/12/20
 */
@RestController
@RequestMapping(produces = "application/json;charset=UTF-8")
@Transactional
@RequiredArgsConstructor
public class CouponController {
    private final CouponService couponService;
    /**
     * 查看优惠券
     * @param user 用户
     * @param used 是否使用
     * @param page 页码
     * @param pageSize 每页数量
     */
    @Audit(departName = "coupons")
    @GetMapping("/coupons")
    public ReturnObject showCoupon(@LoginUser UserDto user,
                                   @RequestParam(required = false, defaultValue = "0") String used,
                                   @RequestParam(required = false, defaultValue = "1") Integer page,
                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        List<Coupon> couponList = couponService.showCoupon(user, Byte.valueOf(used), page, pageSize);
        return new ReturnObject(ReturnNo.OK, new PageVo<>(couponList.stream().map(o -> CloneFactory.copy(new CouponVo(o), o)).toList(), page, pageSize));
    }

    @Audit(departName = "coupons")
    @PostMapping("/couponactivities/{id}/coupons")
    public ReturnObject claimCoupon(@PathVariable Long id,
                                    @LoginUser UserDto user) {
        Coupon coupon = couponService.claimCoupon(id, user);
        return new ReturnObject(ReturnNo.OK, CloneFactory.copy(new CouponVo(coupon), coupon));
    }
}
